package com.zyz.bookborrowing.servlet;

import com.alibaba.fastjson.JSON;
import com.zyz.bookborrowing.bean.Classes;
import com.zyz.bookborrowing.bean.Department;
import com.zyz.bookborrowing.bean.Student;
import com.zyz.bookborrowing.service.*;
import com.zyz.bookborrowing.utils.Constant;
import com.zyz.bookborrowing.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "studentServlet", urlPatterns = "/studentServlet")
public class StudentServlet extends HttpServlet {

    IStudentService studentService = new StudentServiceImpl();
    IDepartmentService departmentService = new DepartmentServiceImpl();

    IClassService classService = new ClassServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1. 获取请求的类型
        String type = req.getParameter(Constant.REQUEST_PARAMETER_TYPE);
//        2. 如果type不为空，那么根据type不同值做出不同操作
        if (StringUtils.isNotEmpty(type)){
            if (Constant.SERVLET_TYPE_QUERY.equals(type)){
                queryList(req, resp);
            } else if (Constant.SERVLET_TYPE_SAVE.equals(type)){
                saveUpStu(req, resp);
            } else if (Constant.SERVLET_TYPE_UPDATE.equals(type)) {
                saveUpStu(req, resp);
            } else if (Constant.SERVLET_TYPE_DELETE.equals(type)) {
                deleteStu(req, resp);
            } else if (Constant.SERVLET_TYPE_QUERYBYID.equals(type)) {
                queryById(req, resp);
            } else if ("saveQueryAll".equals(type)) {
//                需要查询所有的院系信息
                List<Department> depts = departmentService.list(null);
                req.setAttribute("depts", depts);
                req.getRequestDispatcher("/student/studentUpdate.jsp").forward(req, resp);
            } else if ("queryClsByDeptId".equals(type)) {
//                ajax 异步提交，用院系编号得所属班级
                String departId = req.getParameter("deptId");
                List<Classes> classes = classService.queryClsByDepartId(Integer.parseInt(departId));
//                把集合数据转换为json数据响应
                String json = JSON.toJSONString(classes);
                resp.setContentType("application/json;charset=UTF-8");
                PrintWriter writer = resp.getWriter();
                writer.println(json);
                writer.flush();
            } else {
                queryList(req, resp);
            }
        } else {
            queryList(req, resp);
        }
    }

    private void deleteStu(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        studentService.deleteById(Integer.parseInt(id));
        resp.sendRedirect("/studentServlet?type=query");
    }

    private void queryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Student student = studentService.queryById(Integer.parseInt(id));
        List<Department> depts = departmentService.list(null);
        req.setAttribute("depts", depts);
        req.setAttribute("stu", student);
        req.getRequestDispatcher("/student/studentUpdate.jsp").forward(req, resp);
    }

    private void saveUpStu(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Student stu = new Student();
        String id = req.getParameter("id");
        stu.setStuNum(req.getParameter("stuNum"));
        stu.setStuName(req.getParameter("stuName"));
        stu.setPhoneNum(req.getParameter("phoneNum"));
        stu.setGender(req.getParameter("gender"));
        stu.setAddress(req.getParameter("address"));
        String departId = req.getParameter("departId");
        String classId = req.getParameter("classId");
        System.out.println(id);

        if (departId != null){
            stu.setDepartId(Integer.parseInt(departId));
            Department department = departmentService.queryById(stu.getDepartId());
            stu.setDepartName(department.getDepartment());
        }
        if (classId != null){
            stu.setClassId(Integer.parseInt(classId));
            Classes classes = classService.queryById(stu.getClassId());
            stu.setClassName(classes.getClassName());
        }
        Integer count = -1;

        if (id == null || id.equals("")){
//                count:影响的行数
            count = studentService.saveStudent(stu);
        } else {
            stu.setId(Integer.parseInt(id));
            count = studentService.updateStudent(stu);
            System.out.println("更新");
        }
        if (count > 0){
//                    表示增/更成功,再做一次查询操作
            resp.sendRedirect("/studentServlet?type=query");
        } else {
//                    插入失败
            System.out.println("插入失败...");
//                    跳转失败页面
        }
    }

    private void queryList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Student> list = studentService.list(null);
        req.setAttribute("list", list);
        req.getRequestDispatcher("/student/student.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
